package ace.cmp.data.methodname.sql.mybatisplus.core.method;

import ace.cmp.data.methodname.method.name.sql.MethodSqlBuilder;
import ace.cmp.data.methodname.sql.mybatisplus.core.mysql.MethodToSqlMysqlBuilder;
import ace.cmp.data.methodname.sql.mybatisplus.core.properties.MybatisPlugMethodNameToSqlProperties;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import java.lang.reflect.Method;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlSource;
import org.apache.ibatis.scripting.defaults.RawSqlSource;

/**
 * @author caspar
 * @date 2023/2/16 14:13 从方法名，推导sql实现类
 */
@Slf4j
public class MethodNameToSqlExistsMethod extends AbstractMethodNameToSqlMethod {

  private final MethodSqlBuilder sqlBuilder;

  /**
   * @param method      方法名
   * @param tableInfo   表映射
   * @param mapperClass 接口类型
   * @since 3.5.0
   */
  public MethodNameToSqlExistsMethod(
      Method method,
      TableInfo tableInfo,
      Class mapperClass,
      MybatisPlugMethodNameToSqlProperties sqlProperties) {
    super(method, tableInfo, mapperClass, sqlProperties);
    sqlBuilder =
        new MethodToSqlMysqlBuilder(this.getEntityQueryResolver(), tableInfo, sqlProperties);
  }

  @Override
  public MappedStatement injectMappedStatement(
      Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) {
    try {
      String sql = sqlBuilder.getSql();
      SqlSource sqlSource = new RawSqlSource(configuration, sql, Object.class);
      return this.addSelectMappedStatementForOther(mapperClass, sqlSource, method.getReturnType());
    } catch (Exception ex) {
      log.warn(
          "{} method resolve sql fail.reason is exception or not resolve.{}",
          this.getEntityQueryResolver().getMethod().getName(),
          ex.getMessage());
    }
    return null;
  }
}
